//
//  homePageVC.m
//  jiaKaoZhuShou
//
//  Created by 金艺社 on 2018/5/14.
//  Copyright © 2018年 金艺社. All rights reserved.
//

#import "homePageVC.h"
#import "AmapManger.h"
#import "homePageTitleV.h"
#import "driveSchoolModel.h"
#import "driveSchoolCell.h"
#import "driveDetialVC.h"
#import "personalVC.h"
#import "flagModel.h"
#import "selectDriveVC.h"
#import "GKSearchViewController.h"
#import "messageVC.h"
#import "POIModel.h"
#import "NetworkManager.h"
#define WEAK __weak typeof(self)weakSelf = self
@interface homePageVC ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate> {
    UIButton *bottomView;
    UIButton *headSectiuonView;
    UIButton *positioningView;
    AmapManger *Amap;
    
    BOOL isScrren;//列表是否铺满全屏
    
    flagModel *selectModel;//选择城市
    AMapGeoPoint *selectPoint;//默认城市坐标
    NSString *currentCity;//当前定位城市
    
    NSInteger page;
}
@property (nonatomic, strong) homePageTitleV *titleV;
@property (nonatomic, strong) UITableView *DrivingSchoolList;
@property (nonatomic, copy) NSMutableArray *driveSchoolData;
@property (nonatomic, copy) NSMutableArray *flagAry;
@end

@implementation homePageVC
- (void)updateVersion {
    __weak typeof(self)weakSelf = self;
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSDictionary *paramter = @{
                               @"version" : appCurVersion,
                               @"appId" : @"com.bxxueche.stu"
                               };
    NSString *urlStr = [[apiManger shareApiManger] versionNum];
    [[NetworkManager defaultManager] postWithURLString:urlStr parameters:paramter success:^(id responseObject) {
        __strong typeof(self)strongSelf = weakSelf;
        if ([responseObject[@"rcd"] isEqualToString:@"R0001"]) {
            NSString *serviceVersion = responseObject[@"versionName"];
            if ([strongSelf isJumpAppStore:appCurVersion andAppstore:serviceVersion]) {
                [strongSelf showAlertViewTitle:[NSString stringWithFormat:@"检测到新版本%@,是否更新？" ,serviceVersion] subTitle:responseObject[@"description"] openUrl:responseObject[@"url"]];
            }
        }
       
    } failure:^(NSError *error) {
    }];
}
- (BOOL)isJumpAppStore:(NSString *)localVersion andAppstore:(NSString *)appVersion {//比较版本大小
    NSArray *localArray = [localVersion componentsSeparatedByString:@"."];
    NSArray *appArray = [appVersion componentsSeparatedByString:@"."];
    if (localArray.count < appArray.count) {
        return YES;
    }
    NSInteger minArrayLength = MIN(localArray.count, appArray.count);
    BOOL needUpdate = NO;
    for(int i = 0; i < minArrayLength; i++){//以最短的数组长度为遍历次数,防止数组越界
        //取出每个部分的字符串值,比较数值大小
        NSString *localElement = localArray[i];
        NSString *appElement = appArray[i];
        NSInteger  localValue =  localElement.integerValue;
        NSInteger  appValue = appElement.integerValue;
        if(localValue < appValue) {
            //从前往后比较数字大小,一旦分出大小,跳出循环
            needUpdate = YES;
            break;
        }else{
            needUpdate = NO;
        }
    }
    return needUpdate;
}
- (void)showAlertViewTitle:(NSString *)title subTitle:(NSString *)subTitle openUrl:(NSString *)openUrl {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:subTitle preferredStyle:UIAlertControllerStyleAlert];
    //3.1修改title文字的显示样式
    NSMutableAttributedString *titleAttribute = [[NSMutableAttributedString alloc]initWithString:title];
    [titleAttribute addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, titleAttribute.length - 1)];
    [titleAttribute addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, titleAttribute.length - 1)];
    [alertVC setValue:titleAttribute forKey:@"attributedTitle"];
    
    NSMutableAttributedString *attMsgString = [self setMessageStyleWithMessage:subTitle];
    [alertVC setValue:attMsgString forKey:@"attributedMessage"];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUrl] options:@{} completionHandler:^(BOOL success) {
                NSLog(@"成功");
            }];
        }
    }];
    [alertVC addAction:cancel];
    [alertVC addAction:sure];
    [self presentViewController:alertVC animated:YES completion:nil];
}
/* 修改message样式 */
- (NSMutableAttributedString *)setMessageStyleWithMessage:(NSString *)msg {
    NSMutableAttributedString *attMsgString = [[NSMutableAttributedString alloc] initWithString:msg];
    // 设置字体
    [attMsgString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, attMsgString.length)];
    // 设置颜色
    [attMsgString addAttribute:NSForegroundColorAttributeName value:[UIColor gk_colorWithHexString:@"#000000"] range:NSMakeRange(0, attMsgString.length)];
    
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    // 设置行间距
    [paragraph setLineSpacing:3];
    // 设置段间距
    [paragraph setParagraphSpacingBefore:5];
    // 设置对齐方式
    [paragraph setAlignment:NSTextAlignmentLeft];
    // 设置书写方向
    [paragraph setBaseWritingDirection:NSWritingDirectionLeftToRight];
    [attMsgString addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, attMsgString.length)];
    return attMsgString;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = item;
    page = 1;
    Amap = [AmapManger allocWithZone:nil];
    __weak homePageVC *wfSelf = self;
    //热门城市 请求完成后把定位到的城市显示在title
    Amap.infoBlock = ^(AMapLocationReGeocode *Geocode) {
        wfSelf.titleV.titleLable.text = Geocode.city;
        currentCity = Geocode.city;
        //请求flag
        [wfSelf RequestFlag];
    };
    [Amap addToViewWithView:self.view];
    //添加title视图
    _titleV = [[homePageTitleV alloc]initWithFrame:CGRectMake((kScreenWidth - 100)/2, 0, 100, 44)];
    [_titleV.bottomArrowBtn addTarget:self action:@selector(bottomArrowAction:)  forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:_titleV];
    //添加左右item
    [self addLeftAndRightTopBar];
    //添加searchView
    [self addSearchView];
    //添加bottomView
    [self addbottomView];
    //添加PositioningView
    [self addPositioningView];
}
- (void)viewWillAppear:(BOOL)animated {
    [self updateVersion];
    [self updateNagationBarlayout];
}
- (void)viewWillDisappear:(BOOL)animated {
    self.titleV.hidden = YES;
}
#pragma mark --- addSubView
- (void)addLeftAndRightTopBar {
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStyleDone target:self action:@selector(tapLeftButton:)];
    [leftItem setImage:[UIImage imageNamed:@"people"]];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:self action:@selector(tapRightButton:)];
    [rightItem setImage:[UIImage imageNamed:@"messageBleak"]];
    self.navigationItem.rightBarButtonItem = rightItem;
}
- (void)addSearchView {
    UIButton *searchBtn = [UIButton new];
    [searchBtn setTitle:@"搜索附近驾校" forState:0];
    [searchBtn setTitleColor:[UIColor lightGrayColor] forState:0];
    searchBtn.titleLabel.font = [UIFont customFontOfSize:13];
    [searchBtn setImage:[UIImage imageNamed:@"searchGray"] forState:0];
    searchBtn.contentHorizontalAlignment = 1;
    searchBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 60, 0, 0);
    searchBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
    searchBtn.backgroundColor = [UIColor colorWithWhite:1.0f alpha:0.5];
    [searchBtn addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:searchBtn];
    [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(5);
        make.left.equalTo(self.view.mas_left).offset(5);
        make.right.equalTo(self.view.mas_right).offset(-5);
        make.height.equalTo(@45);
    }];
}
- (void)addbottomView {
    bottomView = [UIButton new];
    [bottomView setTitle:@"查看附近驾校" forState:0];
    [bottomView setTitleColor:[UIColor lightGrayColor] forState:0];
    bottomView.titleLabel.font = [UIFont customFontOfSize:17];
    bottomView.contentHorizontalAlignment = 0;
    [bottomView setImage:[UIImage imageNamed:@"topArrow"] forState:0];
    bottomView.backgroundColor = [UIColor colorWithWhite:1.0f alpha:1];
    [bottomView addTarget:self action:@selector(bottomViewAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.height.equalTo(@50);
    }];
    //设置btn title和image 位置
    [bottomView layoutIfNeeded];
    CGSize titleSize = bottomView.titleLabel.bounds.size;
    CGSize imageSize = bottomView.imageView.bounds.size;
    CGFloat interval = 1.0;
    bottomView.imageEdgeInsets = UIEdgeInsetsMake(0,titleSize.width + interval, 0, -(titleSize.width + interval));
    bottomView.titleEdgeInsets = UIEdgeInsetsMake(0, -(imageSize.width + interval), 0, imageSize.width + interval);
}
- (void)addDrivingSchoolList {
    if (self.DrivingSchoolList.hidden) {
        self.DrivingSchoolList.hidden = NO;
    }else {
        [self.view addSubview:self.DrivingSchoolList];
        self.DrivingSchoolList.delegate = self;
        self.DrivingSchoolList.dataSource = self;
        self.DrivingSchoolList.tableFooterView = [UIView new];
        [self.DrivingSchoolList registerNib:[UINib nibWithNibName:NSStringFromClass([driveSchoolCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([driveSchoolCell class])];
        [self addRefresh];
        [_DrivingSchoolList mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view.mas_bottom);
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
            make.height.mas_equalTo(kScreenHeight/2);
        }];
    }
}
//添加头部和底部刷新控件
- (void)addRefresh {
//    self.DrivingSchoolList.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.stateLabel.textColor = [UIColor grayColor];
    footer.stateLabel.font = [UIFont systemFontOfSize:14];
    [footer setTitle:@"没有更多了" forState:MJRefreshStateNoMoreData];
    self.DrivingSchoolList.mj_footer = footer;
    self.DrivingSchoolList.mj_footer.hidden = YES;
}
- (UIButton *)getHeadSectionView {
    if (!headSectiuonView) {
        headSectiuonView = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 25)];
        [headSectiuonView setTitle:@"" forState:0];
        [headSectiuonView setTitleColor:[UIColor lightGrayColor] forState:0];
        headSectiuonView.titleLabel.font = [UIFont customFontOfSize:15];
        headSectiuonView.contentHorizontalAlignment = 0;
        [headSectiuonView setImage:[UIImage imageNamed:@""] forState:0];
        headSectiuonView.backgroundColor = [UIColor whiteColor];
        [headSectiuonView addTarget:self action:@selector(headSectiuonViewAction:) forControlEvents:UIControlEventTouchUpInside];
        [headSectiuonView layoutIfNeeded];
        CGSize titleSize = headSectiuonView.titleLabel.bounds.size;
        CGSize imageSize = headSectiuonView.imageView.bounds.size;
        CGFloat interval = 1.0;
        headSectiuonView.imageEdgeInsets = UIEdgeInsetsMake(0,titleSize.width + interval, 0, -(titleSize.width + interval));
        headSectiuonView.titleEdgeInsets = UIEdgeInsetsMake(0, -(imageSize.width + interval), 0, imageSize.width + interval);
        UIView *bleakLine = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 1)];
        bleakLine.backgroundColor = [UIColor groupTableViewBackgroundColor];
        [headSectiuonView addSubview:bleakLine];
    }
    return headSectiuonView;
}
- (void)addPositioningView {
    positioningView = [UIButton new];
    positioningView.backgroundColor = [UIColor whiteColor];
    [positioningView setImage:[UIImage imageNamed:@"currentPosition"] forState:0];
    [positioningView addTarget:self action:@selector(positioningViewAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:positioningView];
    [positioningView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(bottomView.mas_top).offset(-5);
        make.left.equalTo(self.view.mas_left).offset(25);
        make.height.width.equalTo(@40);
    }];
}
#pragma mark --- updateViewLayout
/**
 update nagation layout
 */
- (void)updateNagationBarlayout {
    UIBarButtonItem *leftItem = self.navigationItem.leftBarButtonItem;
    UIBarButtonItem *rightItem = self.navigationItem.rightBarButtonItem;
    if (isScrren) {
        _titleV.hidden = YES;
        self.title = @"附近驾校";
        [leftItem setImage:[UIImage imageNamed:@"leftArrow"]];
        [rightItem setImage:[UIImage imageNamed:@"searchBleak"]];
    }else {
        _titleV.hidden = NO;
        self.title = @"";
        [leftItem setImage:[UIImage imageNamed:@"people"]];
        [rightItem setImage:[UIImage imageNamed:@"messageBleak"]];
    }
    NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:0];
    [self.DrivingSchoolList reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
}
//PositioningView
- (void)uodatePositioningViewLayout {
    if (self.DrivingSchoolList.hidden) {
        [positioningView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(bottomView.mas_top).offset(-5);
            make.left.equalTo(self.view.mas_left).offset(25);
            make.height.width.equalTo(@40);
        }];
        [positioningView setImage:[UIImage imageNamed:@"currentPosition"] forState:0];
    }else {
        [positioningView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.DrivingSchoolList.mas_top).offset(-5);
            make.left.equalTo(self.view.mas_left).offset(25);
            make.height.width.equalTo(@40);
        }];
        [positioningView setImage:[UIImage imageNamed:@"bluePosition"] forState:0];
    }
}
//map
- (void)updateMapViewFrame {
    //设置动画的名字
    [UIView beginAnimations:@"Animation" context:nil];
    //设置动画的间隔时间
    [UIView setAnimationDuration:0.20];
    //??使用当前正在运行的状态开始下一段动画
    [UIView setAnimationBeginsFromCurrentState: YES];
    //设置视图移动的位移
    CGFloat y;
    if (self.DrivingSchoolList.hidden) {
        y = 0;
    }else {
        y = -80;
    }
    [Amap.mapView setFrame:CGRectMake(self.view.frame.origin.x, y, self.view.frame.size.width, self.view.frame.size.height)];
    //设置动画结束
    [UIView commitAnimations];
}
#pragma mark --- btn action
//选择城市按钮点击事件
- (void)bottomArrowAction:(id)sender {
//    page = 1;
//    [self.driveSchoolData removeAllObjects];
    selectDriveVC *VC = [selectDriveVC new];
    WEAK;
    VC.cityBlock = ^(NSString *city) {//通过选择城市 获取并描点驾校
        weakSelf.titleV.titleLable.text = city;
        for (flagModel *model in weakSelf.flagAry) {
            if ([city isEqualToString:model.name]) {
                selectModel = model;
                [weakSelf locationWithCity:city];
            }
        }
    };
    [VC.selectCity addObjectsFromArray:self.flagAry];
    [self.navigationController pushViewController:VC animated:YES];
}
- (void)locationWithCity:(NSString *)city {
    [Amap searchGeocodeWithCity:city];
    WEAK;
    if ([city isEqualToString:currentCity]) {
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSArray *ary = [user objectForKey:@"currentPoint"];
        NSString *la = ary[0]; NSString *lo = ary[1];
        selectPoint.latitude = la.doubleValue;
        selectPoint.longitude = lo.doubleValue;
        [self driveListRequest];
    }else {
        Amap.pointBlock = ^(AMapGeocode *geo) {
            selectPoint = geo.location;
            //请求列表数据
            [weakSelf driveListRequest];
        };
    }
}
//左上角按钮点击事件
- (void)tapLeftButton:(UIBarButtonItem *)sender {
    if ([UIImagePNGRepresentation(sender.image) isEqual:UIImagePNGRepresentation([UIImage imageNamed:@"leftArrow"])]) {
        [_DrivingSchoolList mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view.mas_bottom);
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
            make.height.mas_equalTo(kScreenHeight/2);
        }];
        isScrren = NO;
        [self updateNagationBarlayout];
    }else {
        personalVC *logVC = [personalVC new];
        [self.navigationController pushViewController:logVC animated:YES];
    }
}
//右上角按钮点击事件
- (void)tapRightButton:(UIBarButtonItem *)sender {
    if ([UIImagePNGRepresentation(sender.image) isEqual:UIImagePNGRepresentation([UIImage imageNamed:@"messageBleak"])]) {
        messageVC *VC = [messageVC new];
        [self.navigationController pushViewController:VC animated:YES];
    }else {
        GKSearchViewController *searchVc = [[GKSearchViewController alloc] init];
        searchVc.laa = [NSString stringWithFormat:@"%f", selectPoint.latitude];
        searchVc.loo = [NSString stringWithFormat:@"%f", selectPoint.longitude];
        searchVc.sign = selectModel.sign;
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:searchVc];
        [self presentViewController:nav animated:YES completion:nil];
    }
}
//搜索按钮点击事件
- (void)searchAction:(id)sender {
    GKSearchViewController *searchVc = [[GKSearchViewController alloc] init];
    searchVc.laa = [NSString stringWithFormat:@"%f", selectPoint.latitude];
    searchVc.loo = [NSString stringWithFormat:@"%f", selectPoint.longitude];
    searchVc.sign = selectModel.sign;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:searchVc];
    [self presentViewController:nav animated:YES completion:nil];
}
//底部按钮事件
- (void)bottomViewAction:(id)sender {
    //请求列表数据
    [self driveListRequest];
    //添加DrivingSchoolList
    [self addDrivingSchoolList];
    [self uodatePositioningViewLayout];
    [self updateMapViewFrame];
}
- (void)headSectiuonViewAction:(id)sender {//不使用
}
// 重新定位
- (void)positioningViewAction:(id)sender {
    [Amap reGeocodeAction];
}

#pragma mark --- UItableView DataSource and delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.driveSchoolData.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 75;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    driveSchoolCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([driveSchoolCell class])];
    cell.model = self.driveSchoolData[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    driveSchoolModel *model = [self.driveSchoolData objectAtIndex:indexPath.row];
    driveDetialVC *detial = [driveDetialVC new];
    detial.ID = model.id;
    detial.distance = model.distance;
    typeof(self) weak = self;
    detial.locationBlk = ^(NSString *name) {
        [weak->Amap selectPointWithName:name];
        
        
        
        
    };
    [self.navigationController pushViewController:detial animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if ([self.title isEqualToString:@"附近驾校"]) {
        return 0;
    }
    return 25;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if ([self.title isEqualToString:@"附近驾校"]) {
        return [self getHeadSectionView];
    }
    return  [[NSBundle mainBundle] loadNibNamed:@"tableSectionHeadView" owner:nil options:nil ].lastObject;
}

#pragma mark --- uiscrollowViewDelegate
/**
 停止拖拽回调
 */
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if ([scrollView isKindOfClass:[UITableView class]] && _DrivingSchoolList.frame.size.height < self.view.frame.size.height) {
        if (scrollView.contentOffset.y < 0) {
            scrollView.hidden = YES;
            [self uodatePositioningViewLayout];
            [self updateMapViewFrame];
        }else if (scrollView.contentOffset.y > 0) {
            [UIView animateWithDuration:0.5 animations:^{
                /** 需要执行动画的代码 **/
                [_DrivingSchoolList mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.left.bottom.right.equalTo(self.view);
                }];
            }];
            isScrren = YES;
            [self updateNagationBarlayout];
        }
    }else if ([scrollView isKindOfClass:[UITableView class]] && _DrivingSchoolList.frame.size.height == self.view.frame.size.height) {
        if (scrollView.contentOffset.y < -20) {
            [UIView animateWithDuration:0.5 animations:^{
                /** 需要执行动画的代码 **/
                [_DrivingSchoolList mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.bottom.equalTo(self.view.mas_bottom);
                    make.left.equalTo(self.view.mas_left);
                    make.right.equalTo(self.view.mas_right);
                    make.height.mas_equalTo(kScreenHeight/2);
                }];
            }];
            isScrren = NO;
            [self updateNagationBarlayout];
        }else if (scrollView.contentOffset.y > 0) {
            
        }
    }
}

#pragma mark --- request data
// requestFlag
- (void)RequestFlag {
    __weak typeof(self)weakSelf = self;
    [networkManger PostHttpDataWithUrlStr:[[apiManger shareApiManger] driveFlag] Dic:nil SuccessBlock:^(id responseObject) {
        if ([responseObject[@"rcd"] isEqualToString:R0001]) {
            weakSelf.flagAry  = [flagModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [weakSelf showCity:weakSelf.flagAry];
        }
    } FailureBlock:^(id error) {
        [MBProgressHUD gk_toastShowMessage:@"请求失败"];
    }];
}
//需要展示城市计算
- (void)showCity:(NSMutableArray *)ary {
    BOOL isHave = NO;
    for (flagModel *model in ary) {
        if ([self.titleV.titleLable.text isEqualToString:model.name]) {
            self.titleV.titleLable.text = model.name;
            selectModel = model;
            isHave = YES;
        }
    }
    if (!isHave) {
        selectModel = ary[0];
        self.titleV.titleLable.text = selectModel.name;
    }
    if (isHave) { //如果热门城市（拥有合作驾校的城市）有当前定位城市，计算驾校距离传入坐标使用当前位置坐标，否则使用高的地图反地理编码坐标
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSArray *ary = [user objectForKey:@"currentPoint"];
        NSString *la = ary[0]; NSString *lo = ary[1];
        selectPoint = [AMapGeoPoint new];
        selectPoint.latitude = la.doubleValue;
        selectPoint.longitude = lo.doubleValue;
        //默认点击一次“查看附近驾校”按钮
        [self bottomViewAction:bottomView];
    }else {
        [Amap searchGeocodeWithCity:self.titleV.titleLable.text];
        typeof(self) weakS = self;
        Amap.pointBlock = ^(AMapGeocode *geo) {
            selectPoint = geo.location;
            //默认点击一次“查看附近驾校”按钮
            [weakS bottomViewAction:weakS->bottomView];
        };
    }
}
- (void)loadMoreData {
    page++;
    [self driveListRequest];
}
// driveList
- (void)driveListRequest {
    
    NSString *la = [NSString stringWithFormat:@"%f", selectPoint.latitude];
    NSString *lo = [NSString stringWithFormat:@"%f", selectPoint.longitude];
    NSDictionary *dic = @{
          @"pager.pageNumber":@(page),
          @"pager.pageSize":@500,
          @"latitude":lo == nil ? @"" : la,
          @"longitude":la == nil ? @"" : lo,
          @"city":selectModel.sign == nil ? @"" : selectModel.sign,
          };
    __weak typeof(self)weakSelf = self;
    [networkManger PostHttpDataWithUrlStr:[[apiManger shareApiManger] drivcList] Dic:dic SuccessBlock:^(id responseObject) {
        if ([responseObject[@"rcd"] isEqualToString:R0001]) {
            weakSelf.driveSchoolData = [driveSchoolModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"result"]];
            
            
            
            NSMutableArray *GeoPointAry = [NSMutableArray array];
            if (weakSelf.driveSchoolData.count == 0) {
                [MBProgressHUD gk_toastShowMessage:@"没有驾校信息"];
                return;
            }
            int count = weakSelf.driveSchoolData.count >= 10 ? 10 : (int)weakSelf.driveSchoolData.count;
            for (int i = 0; i < count; i++) {
                driveSchoolModel *model = weakSelf.driveSchoolData[i];
                POIModel *poimodel = [POIModel new];
                AMapGeoPoint *point = [AMapGeoPoint new];
                point.latitude = [model.latitude floatValue];
                point.longitude = [model.longitude floatValue];
                poimodel.geoPoint = point;
                poimodel.name = model.companyName;
                poimodel.distanse = model.distance;
                [GeoPointAry addObject:poimodel];
            }
            
            [weakSelf structureAmapPOIWith:GeoPointAry];
            [weakSelf.DrivingSchoolList reloadData];
        }else {
            [MBProgressHUD gk_toastShowMessage:responseObject[@"rmg"]];
        }
    } FailureBlock:^(id error) {
        [MBProgressHUD gk_toastShowMessage:@"请求失败"];
    }];
}

//构造高德地图描点需要的 AmapPOI 类型(用于描点)
- (void)structureAmapPOIWith:(NSMutableArray *)ary {
    NSMutableArray *poiAry = [NSMutableArray array];
    for (POIModel *m in ary) {
         AMapPOI *POI = [AMapPOI new];
         POI.location = m.geoPoint;
         POI.name = m.name;
         POI.distance = m.distanse.integerValue;
        [poiAry addObject:POI];
    }
    [Amap tracingPointWithAry:(NSArray *)poiAry];
}
//传入城市名字得到城市的首字母拼音 如：杭州 -> HZ
- (NSString *)getCityNameZiMu:(NSString *)city {
    NSString *zimu = @"";
    if (![city isEqualToString:@"当前位置"]) {
        NSString *a = [city substringToIndex:(city.length - 1)];
        NSMutableArray *array = [NSMutableArray array];
        for (int i = 0; i < a.length; i++) {
            NSRange range = NSMakeRange(i, 1);
            NSString *b = [a substringWithRange:range];
            [array addObject:b];
        }
        for (NSString *b in array) {
            NSString *c = [NSString firstCharactor:b];
            zimu = [NSString stringWithFormat:@"%@%@", zimu, c];
        }
    }
    return zimu;
}

#pragma mark --- 懒加载
- (UITableView *)DrivingSchoolList {
    if (!_DrivingSchoolList) {
        _DrivingSchoolList = [UITableView new];
    }
    return _DrivingSchoolList;
}
- (NSMutableArray *)driveSchoolData {
    if (!_driveSchoolData) {
        _driveSchoolData = [NSMutableArray array];
    }
    return _driveSchoolData;
}
- (NSMutableArray *)flagAry {
    if (!_flagAry) {
        _flagAry = [NSMutableArray array];
    }
    return _flagAry;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
